//
//  DebugMainViewLayout.swift
//  YKSwiftDebugManager
//
//  Created by linghit on 2021/12/2.
//

import UIKit

internal class DebugMainViewLayout: UICollectionViewFlowLayout {
    private var layoutAttributes:Array<UICollectionViewLayoutAttributes> = []
    private var lastMaxY:CGFloat = 0
    private var maxHeight:CGFloat = 0
    
    override func prepare() {
        super.prepare()
        let sections = self.collectionView!.numberOfSections
        self.lastMaxY = 0
        for i in 0..<sections {
            let layoutHeader = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, with: IndexPath(row: 0, section: i))
            layoutHeader.frame = CGRect(x: 0, y: self.lastMaxY, width: self.collectionView!.bounds.size.width, height: 20)
            self.layoutAttributes.append(layoutHeader)
            self.lastMaxY = self.lastMaxY + 20
            let itemCount = self.collectionView!.numberOfItems(inSection: i)
            for j in 0..<itemCount {
                let indexPath = IndexPath(row: j, section: i)
                let attr = self.layoutAttributesForItem(at: indexPath)
                self.layoutAttributes.append(attr!)
                if j == itemCount - 1 {
                    self.lastMaxY = attr!.frame.maxY
                }
            }
            if i == sections - 1 {
                self.maxHeight = self.lastMaxY
            }
        }
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return self.layoutAttributes
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attri = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        var attriX:CGFloat = 0
        var attriY:CGFloat = self.lastMaxY
        var attriWidth:CGFloat = 0
        var attriHeigh:CGFloat = 0
        var line:NSInteger = 0
        var lineItem:NSInteger = 0
        if indexPath.section == 0 {
            lineItem = indexPath.item % 3
            line = indexPath.item / 3
            attriWidth = self.collectionView!.bounds.size.width / 3
            attriHeigh = 50
            attriY = attriY + CGFloat(line) * attriHeigh
            attriX = CGFloat(lineItem) * attriWidth
        }else{
            lineItem = indexPath.item % 4
            line = indexPath.item / 4
            attriWidth = self.collectionView!.bounds.size.width / 4
            attriHeigh = attriWidth
            attriY = attriY + CGFloat(line) * attriHeigh
            attriX = CGFloat(lineItem) * attriWidth
        }
        attri.frame = CGRect(x: attriX, y: attriY, width: attriWidth, height: attriHeigh)
        
        return attri
    }
}
